from rest_framework import serializers
from .models import User, FoodCategory, Food, FoodImage, FoodSpec, CartItem, Order, OrderItem, Address


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'openid', 'avatar', 'phone', 'date_joined']
        read_only_fields = ['id', 'date_joined']


class FoodSpecSerializer(serializers.ModelSerializer):
    class Meta:
        model = FoodSpec
        fields = ['id', 'name', 'extra_price', 'is_default']


class FoodImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = FoodImage
        fields = ['id', 'image_url']


class SimpleFoodSerializer(serializers.ModelSerializer):
    """用于列表展示的简化食品序列化器"""
    image_url = serializers.SerializerMethodField()
    
    class Meta:
        model = Food
        fields = ['id', 'name', 'price', 'original_price', 'image', 'image_url', 'sold', 'rating', 'is_hot', 'is_new']
    
    def get_image_url(self, obj):
        if obj.image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.image.url)
            return obj.image.url
        return obj.image_url


class FoodDetailSerializer(serializers.ModelSerializer):
    """详细的食品序列化器，包含规格和图片"""
    specs = FoodSpecSerializer(many=True, read_only=True)
    images = FoodImageSerializer(many=True, read_only=True)
    category_name = serializers.CharField(source='category.name', read_only=True)
    image_url = serializers.SerializerMethodField()
    
    class Meta:
        model = Food
        fields = ['id', 'name', 'category', 'category_name', 'description', 'price', 
                  'original_price', 'image', 'image_url', 'sold', 'rating', 'is_hot', 'is_new', 
                  'specs', 'images', 'created_at']
    
    def get_image_url(self, obj):
        if obj.image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.image.url)
            return obj.image.url
        return obj.image_url


class CategorySerializer(serializers.ModelSerializer):
    icon_url = serializers.SerializerMethodField()
    
    class Meta:
        model = FoodCategory
        fields = ['id', 'name', 'icon', 'icon_url', 'sort_order']
    
    def get_icon_url(self, obj):
        if obj.icon:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.icon.url)
            return obj.icon.url
        return obj.icon_url


class CategoryWithFoodsSerializer(serializers.ModelSerializer):
    """包含食品列表的分类序列化器"""
    foods = serializers.SerializerMethodField()
    icon_url = serializers.SerializerMethodField()
    
    class Meta:
        model = FoodCategory
        fields = ['id', 'name', 'icon', 'icon_url', 'sort_order', 'foods']
    
    def get_foods(self, obj):
        # 从上下文中获取食品列表，如果没有则返回空列表
        foods = self.context.get('foods', [])
        return SimpleFoodSerializer(foods, many=True, context=self.context).data
    
    def get_icon_url(self, obj):
        if obj.icon:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.icon.url)
            return obj.icon.url
        return obj.icon_url


class CartItemSerializer(serializers.ModelSerializer):
    food_info = SimpleFoodSerializer(source='food', read_only=True)
    spec_name = serializers.CharField(source='spec.name', read_only=True)
    unit_price = serializers.SerializerMethodField()
    total_price = serializers.SerializerMethodField()
    
    class Meta:
        model = CartItem
        fields = ['id', 'food', 'food_info', 'spec', 'spec_name', 'count', 
                  'is_checked', 'unit_price', 'total_price', 'updated_at']
        read_only_fields = ['id', 'updated_at', 'unit_price', 'total_price']
    
    def get_unit_price(self, obj):
        return obj.price
    
    def get_total_price(self, obj):
        return obj.total_price


class AddressSerializer(serializers.ModelSerializer):
    complete_address = serializers.SerializerMethodField()
    
    class Meta:
        model = Address
        fields = ['id', 'name', 'phone', 'province', 'city', 'district', 
                  'detail', 'complete_address', 'is_default', 'updated_at']
        read_only_fields = ['id', 'updated_at']
    
    def get_complete_address(self, obj):
        return f"{obj.province}{obj.city}{obj.district}{obj.detail}"


class OrderItemSerializer(serializers.ModelSerializer):
    total_price = serializers.SerializerMethodField()
    food_image_url = serializers.SerializerMethodField()
    
    class Meta:
        model = OrderItem
        fields = ['id', 'food', 'food_name', 'food_image', 'food_image_url', 'food_price', 
                  'spec', 'count', 'total_price']
        read_only_fields = ['id', 'total_price', 'food_image_url']
    
    def get_total_price(self, obj):
        return obj.total_price
    
    def get_food_image_url(self, obj):
        if obj.food_image:
            request = self.context.get('request')
            if request and not obj.food_image.startswith('http'):
                return request.build_absolute_uri(obj.food_image)
        return obj.food_image


class OrderSerializer(serializers.ModelSerializer):
    """订单序列化器"""
    status_text = serializers.SerializerMethodField()
    address_info = serializers.SerializerMethodField()
    items = OrderItemSerializer(many=True, read_only=True)
    
    class Meta:
        model = Order
        fields = ['id', 'order_number', 'status', 'status_text', 'total_price',
                 'created_at', 'address_info', 'items', 'paid_at', 'delivered_at', 
                 'received_at', 'finished_at', 'canceled_at']
    
    def get_status_text(self, obj):
        status_dict = dict(Order.ORDER_STATUS)
        return status_dict.get(obj.status, "未知状态")
    
    def get_address_info(self, obj):
        if obj.address:
            return {
                "name": obj.address.name,
                "phone": obj.address.phone,
                "address": f"{obj.address.province}{obj.address.city}{obj.address.district}{obj.address.detail}"
            }
        return {
            "table_number": obj.table_number
        }


class OrderCreateSerializer(serializers.ModelSerializer):
    """订单创建序列化器"""
    cart_item_ids = serializers.ListField(child=serializers.IntegerField(), write_only=True)
    table_number = serializers.CharField(write_only=True, required=True)
    
    class Meta:
        model = Order
        fields = ['cart_item_ids', 'table_number', 'remark']
    
    def create(self, validated_data):
        cart_item_ids = validated_data.pop('cart_item_ids')
        table_number = validated_data.pop('table_number')
        user = self.context['request'].user
        
        # 获取购物车项
        cart_items = CartItem.objects.filter(id__in=cart_item_ids, user=user, is_checked=True)
        if not cart_items:
            raise serializers.ValidationError({"cart_item_ids": "购物车不能为空"})
        
        # 计算总价
        total_price = sum(item.total_price for item in cart_items)
        
        # 生成订单号 - 简单实现，实际应该更复杂
        import datetime
        import random
        now = datetime.datetime.now()
        order_number = f"OD{now.strftime('%Y%m%d%H%M%S')}{random.randint(1000, 9999)}"
        
        # 创建订单
        try:
            order = Order.objects.create(
                user=user,
                order_number=order_number,
                total_price=total_price,
                status=1,  # 待确认
                table_number=table_number,  # 设置桌号/取餐号
                remark=validated_data.get('remark', ''),
            )
        except Exception as e:
            raise serializers.ValidationError({"order_creation": str(e)})
        
        # 创建订单项
        order_items = []
        for cart_item in cart_items:
            order_items.append(OrderItem(
                order=order,
                food=cart_item.food,
                food_name=cart_item.food.name,
                food_image=cart_item.food.get_image or '',
                food_price=cart_item.price,
                spec=cart_item.spec.name if cart_item.spec else None,
                count=cart_item.count
            ))
        
        OrderItem.objects.bulk_create(order_items)
        
        # 删除购物车项
        cart_items.delete()
        
        return order 